using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms.Design;
using PickGold.Charting.Utilities;

namespace PickGold.Charting.Design
{
	internal class KeywordsStringEditor : UITypeEditor
	{
		private IWindowsFormsEditorService _edSvc;

		public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
			if (((context != null) && (context.Instance != null)) && ((provider != null) && (context.PropertyDescriptor != null)))
			{
				this._edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
				if (this._edSvc == null)
				{
					return value;
				}
				Series series = null;
				Chart chart = null;
				object instance = context.Instance;
				if (instance is Series)
				{
					series = (Series)instance;
				}
				else if (instance is DataPoint)
				{
					series = ((DataPoint)instance).series;
				}
				else if (instance is LegendItem)
				{
					if (((LegendItem)instance).Common != null)
					{
						chart = ((LegendItem)instance).Common.Chart;
						if (((LegendItem)instance).Common.DataManager.Series.IndexOf(((LegendItem)instance).SeriesName) >= 0)
						{
							series = ((LegendItem)instance).Common.DataManager.Series[((LegendItem)instance).SeriesName];
						}
					}
				}
				else if (instance is LegendCellColumn)
				{
					if (((LegendCellColumn)instance).Legend != null)
					{
						chart = ((LegendCellColumn)instance).Legend.Common.Chart;
					}
				}
				else if (instance is Annotation)
				{
					chart = ((Annotation)instance).Chart;
					if (((Annotation)instance).AnchorDataPoint != null)
					{
						series = ((Annotation)instance).AnchorDataPoint.series;
					}
					else if ((chart != null) && (chart.Series.Count > 0))
					{
						series = chart.Series[0];
					}
				}
				if ((chart == null) && (series != null))
				{
					chart = series.Chart;
				}
				int num = 9;
				if (series != null)
				{
					num = series.YValuesPerPoint - 1;
				}
				else if (chart != null)
				{
					num = 0;
					foreach (Series series2 in chart.Series)
					{
						num = Math.Max(num, series2.YValuesPerPoint - 1);
					}
				}
				KeywordsStringEditorForm dialog = new KeywordsStringEditorForm((string)value, instance.GetType().Name, context.PropertyDescriptor.Name, num);
				if (chart != null)
				{
					dialog.KeywordsRegistry = (KeywordsRegistry)chart.GetService(typeof(KeywordsRegistry));
				}
				this._edSvc.ShowDialog(dialog);
				value = dialog.ResultString;
			}
			return value;
		}

		public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
		{
			if ((context != null) && (context.Instance != null))
			{
				return UITypeEditorEditStyle.Modal;
			}
			return base.GetEditStyle(context);
		}
	}
}

